import * as types from '../constants/ActionTypes';
import _ from 'lodash';

const initialState = {
  selectedZone: {},
  selectedMenu: {},
  selectedSubmenu: {},
  zones: [],
  topics: [],
  topic: {},
  replies: {},
};

export default function (state = initialState, action) {
  const { payload, error, meta = {}, type } = action;
  const { sequence = {}, selectedMenu = {}, id = '0', topicId = '0', replyId = '0', userId = '0', content = '', user = {} } = meta;

  if (sequence.type === 'start' || error) {
    return state;
  }

  switch (action.type) {
    case types.GET_ZONES:
      const data = action.payload;
	  return {
    ...state,
    zones: payload.zones,
    selectedZone: payload.selectedZone,
    selectedMenu: payload.selectedMenu,
    selectedSubmenu: payload.selectedSubmenu,
    topics: payload.topics,
	  };
    case types.GET_TOPICS_BY_MENU:
	  return {
	    ...state,
	    topics: payload,
	    selectedMenuKey: selectedMenu.selectedMenuKey,
	    selectedSubmenuKey: selectedMenu.selectedSubmenuKey,
	  };
    case types.UPDATE_MENU:
	  return {
	  	...state,
	  	selectedMenuKey: payload.selectedMenuKey,
	  	selectedSubmenuKey: payload.selectedSubmenuKey,
	  };
    case types.GET_TOPIC_BY_ID:
	  return {
    ...state,
    topic: payload.topic,
	  };
    case types.GET_REPLIES_BY_TOPIC_ID:
      {
        const replies = payload.replies;

        replies.forEach((item) => {
          const index = _.findIndex(payload.authors, i => i._id === item.author_id);

          if (index >= 0) {
            item.author = payload.authors[index];
          }
        });

	  return {
	    ...state,
    replies: {
     	  currentPage: payload.currentPage,
     	  pages: payload.pages,
     	  replies,
    },
	  };
      }
    case types.GET_MORE_REPLIES_BY_TOPIC_ID:
      {
        const replies = payload.replies;

        replies.forEach((item) => {
          const index = _.findIndex(payload.authors, i => i._id === item.author_id);

          if (index >= 0) {
            item.author = payload.authors[index];
          }
        });

        return {
          ...state,
          replies: {
            currentPage: payload.currentPage,
            pages: payload.pages,
            replies: state.replies.replies.concat(replies),
          },
        };
      }
    case types.SUBMIT_REPLY:
      {
        const reply = payload.reply;
        return {
          ...state,
          replies: {
            ...state.replies,
            replies: [].concat(reply, state.replies.replies),
          },
        };
      }
    default:
      return state;
  }
}
